<template>
  <div class="pic-manage">
    <div class="page-header">
      <h2>图片管理</h2>
      <el-button type="primary" icon="el-icon-upload" @click="showUploadDialog">上传图片</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-box">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="房源标题">
          <el-input v-model="searchForm.houseTitle" placeholder="请输入房源标题" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 图片网格展示 -->
    <div class="pic-grid" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="4" v-for="pic in picList" :key="pic.id">
          <el-card class="pic-card" shadow="hover">
            <div class="pic-image">
              <el-image
                :src="pic.url"
                fit="cover"
                style="width: 100%; height: 150px;"
                :preview-src-list="[pic.url]"
              ></el-image>
            </div>
            <div class="pic-info">
              <p class="pic-title" :title="pic.houseTitle">{{ pic.houseTitle || '未知房源' }}</p>
              <el-tag size="mini" :type="pic.isMain ? 'success' : 'info'">
                {{ pic.isMain ? '主图' : '附图' }}
              </el-tag>
            </div>
            <div class="pic-actions">
              <el-button size="mini" type="primary" icon="el-icon-view" @click="handlePreview(pic)">预览</el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(pic)">删除</el-button>
            </div>
            <div class="pic-time">{{ pic.createTime || '未知时间' }}</div>
          </el-card>
        </el-col>
      </el-row>
      <el-empty v-if="!loading && picList.length === 0" description="暂无图片"></el-empty>
    </div>

    <!-- 分页 -->
    <div class="pagination-box" v-if="total > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="[12, 24, 48, 96]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 上传对话框 -->
    <el-dialog title="上传房源图片" :visible.sync="uploadDialogVisible" width="50%">
      <el-form :model="uploadForm" :rules="uploadRules" ref="uploadForm" label-width="100px">
        <el-form-item label="选择房源" prop="houseId">
          <el-select v-model="uploadForm.houseId" placeholder="请选择房源" style="width: 100%;" filterable>
            <el-option
              v-for="house in myHouses"
              :key="house.id"
              :label="house.title"
              :value="house.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否主图">
          <el-switch v-model="uploadForm.isMain"></el-switch>
        </el-form-item>
        <el-form-item label="选择图片">
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemoveUpload"
            :file-list="fileList"
            :limit="5"
            accept="image/*">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">支持jpg、png格式，单张最大5MB，最多5张</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {base} from "../config";

export default {
  name: "PicManage",
  data(){
    return{
      loading: false,
      searchForm: {
        houseTitle: ''
      },
      picList: [],
      pageNo: 1,
      pageSize: 12,
      total: 0,
      uploadDialogVisible: false,
      uploadForm: {
        houseId: null,
        isMain: false
      },
      uploadRules: {
        houseId: [{ required: true, message: '请选择房源', trigger: 'change' }]
      },
      uploadUrl: base.baseUrl + '/api/house/uploadPic',
      uploadHeaders: {},
      fileList: [],
      myHouses: []
    }
  },
  methods:{
    loadData() {
      this.loading = true
      // 获取我的房源，然后提取所有图片
      this.$network.findHouseByRole({ role: 1, pageNo: 1, pageSize: 999 }).then(res => {
        if (res.data.code === 200) {
          const houses = res.data.data.list || []
          this.picList = []
          
          // 从每个房源中提取图片
          houses.forEach(house => {
            if (house.picList && house.picList.length > 0) {
              house.picList.forEach(pic => {
                this.picList.push({
                  ...pic,
                  houseTitle: house.title,
                  houseId: house.id
                })
              })
            }
          })
          
          // 如果有搜索条件，进行筛选
          if (this.searchForm.houseTitle) {
            this.picList = this.picList.filter(pic =>
              pic.houseTitle && pic.houseTitle.includes(this.searchForm.houseTitle)
            )
          }
          
          // 计算总数和分页
          this.total = this.picList.length
          const start = (this.pageNo - 1) * this.pageSize
          const end = start + this.pageSize
          this.picList = this.picList.slice(start, end)
        } else {
          this.$message.error(res.data.message || '获取图片列表失败')
        }
      }).catch(error => {
        console.error('获取图片列表失败:', error)
        this.$message.error('获取图片列表失败')
      }).finally(() => {
        this.loading = false
      })
    },
    loadMyHouses() {
      // 加载我的房源列表用于上传
      this.$network.findHouseByRole({ role: 1, pageNo: 1, pageSize: 999 }).then(res => {
        if (res.data.code === 200) {
          this.myHouses = res.data.data.list || []
        }
      }).catch(error => {
        console.error('获取房源列表失败:', error)
      })
    },
    handleSearch() {
      this.pageNo = 1
      this.loadData()
    },
    handleReset() {
      this.searchForm.houseTitle = ''
      this.pageNo = 1
      this.loadData()
    },
    handlePreview(pic) {
      // el-image的preview功能会自动处理
    },
    handleDelete(pic) {
      this.$confirm('确定删除这张图片吗？删除后无法恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用删除图片API
        // this.$network.deletePicById(pic.id).then(res => {
        //   if (res.data.code === 200) {
        //     this.$message.success('删除成功')
        //     this.loadData()
        //   } else {
        //     this.$message.error(res.data.message || '删除失败')
        //   }
        // }).catch(error => {
        //   console.error('删除图片失败:', error)
        //   this.$message.error('删除失败')
        // })
        
        this.$message.info('删除功能需要后端提供 DELETE /api/pic/{id} 接口')
      }).catch(() => {})
    },
    showUploadDialog() {
      this.uploadDialogVisible = true
      this.uploadForm = {
        houseId: null,
        isMain: false
      }
      this.fileList = []
      this.loadMyHouses()
      this.$nextTick(() => {
        this.$refs.uploadForm && this.$refs.uploadForm.clearValidate()
      })
    },
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$message.success('上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
        // 移除上传失败的文件
        const index = fileList.indexOf(file)
        if (index > -1) {
          fileList.splice(index, 1)
        }
      }
    },
    handleRemoveUpload(file, fileList) {
      // 从已上传列表中移除
    },
    submitUpload() {
      this.$refs.uploadForm.validate(valid => {
        if (valid) {
          if (this.fileList.length === 0) {
            this.$message.warning('请先上传图片')
            return
          }
          this.$message.success('图片上传完成')
          this.uploadDialogVisible = false
          this.loadData()
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.pageNo = val
      this.loadData()
    }
  },
  created() {
    // 设置上传header
    const token = localStorage.getItem('token')
    if (token) {
      this.uploadHeaders = { token }
    }
  },
  beforeMount() {
    this.loadData()
  }
}
</script>

<style scoped>
.pic-manage {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
  color: #333;
}

.search-box {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.pic-grid {
  min-height: 400px;
}

.pic-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
}

.pic-card:hover {
  transform: translateY(-5px);
}

.pic-info {
  padding: 10px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pic-title {
  margin: 0;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  margin-right: 10px;
}

.pic-actions {
  display: flex;
  gap: 5px;
  margin-top: 10px;
}

.pic-actions .el-button {
  flex: 1;
  padding: 7px 0;
}

.pic-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  text-align: center;
}

.pagination-box {
  margin-top: 20px;
  text-align: center;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
